/**
 * Copyright © 2009 Qasky. All rights reserved.
 *
 * 项目路由配置
 *
 * @author Wang Hongya
 * @version 0.0.0 2019/10/14
 *
 * History:
 * (author, date, desc)
 * (Wang Hongya, 20191014, 添加注释)
 */
import Vue from 'vue'
import Util from '../libs/util'
import VueRouter from 'vue-router'
import {appRouter, dynamicAppRouter, otherRouter, routers} from './router'
import {loadDynamicAppMenu, loadDynamicOtherAppMenu} from '@/api/dynamicMenu'
import Main from '../views/Main';
import store from '../store'
import axios from "axios";
import { registerMicroApps, start, setDefaultMountApp } from 'qiankun'
const _import = require ('./import')
const portList = [
  {name:'auth1.0',port: "19000"},
  {name:'audit1.0',port: "19001"},
  {name:'sysconf1.0',port: "19002"},
  {name:'sysstyle1.0',port: "19005"},
  {name:'lab1.0',port: "19008"},
]
let uurl = 'localhost'
if(process.env.NODE_ENV === 'production'){
  uurl =window.location.host
}
Vue.use (VueRouter)
/* 路由配置 */
const RouterConfig = {
  routes: routers,
}
let isLoaderFirst = true
export const router = new VueRouter (RouterConfig)

/*******************************************************************************
 * Function    : beforeEach
 * Description : 跳转前的过滤
 * Input       : to, 转到的界面
 *               from, 本来的界面
 *               next, 下一个界面
 * Return      : None
 *******************************************************************************/
router.beforeEach (( to, from, next ) => {
    Util.title (to.meta.title)
    if (!sessionStorage.getItem ('user') && to.name === 'login') {
        next ()
    } else if (!sessionStorage.getItem ('user') && to.name !== 'login') { // 判断是否已经登录且前往的页面不是登录页
        next ({
            name: 'login'
        })
    } else if (sessionStorage.getItem ('user') && to.name === 'home') { // 判断是否已经登录且前往的是登录页
        window.location.reload ()
        next ({
            name: 'login'
        })
    } else {
        if (!router.options.isLoadRouteAndMenu && isLoaderFirst) {
            isLoaderFirst = false
            axios.get ('/auth/getNacosServerInstanceDetail').then (response => {
                response = response.data;
                let data = response.data
                let newList = response.data
                for(let i = 0; i<newList.length-1;i++){
                    for(let j = i+1; j<newList.length;j++){
                        if(newList[i].serverNameAndWebVersion === newList[j].serverNameAndWebVersion){
                            newList.splice(j,1)
                            j--
                        }
                    }
                }
                sessionStorage.setItem('subMicro',JSON.stringify(newList))
                let microApps = []
                if(data.length >0){
                    newList.forEach((item,index)=>{
                        let obj = {}
                        obj.name =item.serverNameAndWebVersion
                        if(process.env.NODE_ENV === 'development'){
                            let target = portList.filter(itm=>itm.name === item.serverNameAndWebVersion)[0]
                            uurl ='localhost:'+(target.port)
                        }
                        obj.entry = '//'+uurl+'/subapp/'+item.serverNameAndWebVersion+'/'
                        obj.activeRule =  '/#/micrApp/'+item.serverNameAndWebVersion
                        microApps.push(obj)
                    })
                }
                setTimeout(()=>{
                    let globalMicro = microApps.map(item => {
                        return {
                            ...item,
                            container: '#subapp-viewport', // 子应用挂载的div
                            props: {
                                routerBase: item.activeRule, // 下发基础路由
                                getGlobalState: store.getGlobalState, // 下发getGlobalState方法
                            }
                        }
                    })
                    // 给子应用配置加上loader方法
                    const apps = globalMicro.map(item => {
                        return {
                            ...item
                        }
                    })
                    registerMicroApps(apps, {
                        beforeLoad: app => {
                            console.log('before load app.name====>>>>>', app.name)
                        },
                        beforeMount: [
                            app => {
                                console.log('[LifeCycle] before mount %c%s', 'color: green;', app.name)
                            }
                        ],
                        afterMount: [
                            app => {
                                console.log('[LifeCycle] after mount %c%s', 'color: green;', app.name)
                            }
                        ],
                        afterUnmount: [
                            app => {
                                console.log('[LifeCycle] after unmount %c%s', 'color: green;', app.name)
                            }
                        ]
                    })
                    setDefaultMountApp('/')
                    start({
                        prefetch:false,//开启预加载
                        /*sandbox:{
                            experimentalStyleIsolation:true
                        },*/
                    });//开启

                    let subMicro = sessionStorage.getItem('subMicro')
                    try{
                        let subMicroItem = JSON.parse(subMicro)
                        subMicroItem.forEach(item=>{
                            router.addRoute ({
                                //path: '/micrApp/'+item.serverNameAndWebVersion+'/*',
                                path: '/micrApp/'+item.serverNameAndWebVersion+'/:patMatch(.*)',
                                name: 'Main',
                                component: Main,
                                children: []
                            })
                        })
                    }catch (e) {

                    }
                    // 加载动态APP路由
                    loadDynamicAppMenu ().then (( {data} ) => {
                        return new Promise (( resolve ) => {
                            if (data && data.code === 0) {
                                let newDate = [...data.data]
                                fnAddDynamicMenuRoutes (newDate)
                                router.options.isLoadRouteAndMenu = true
                                sessionStorage.setItem ('menuList', JSON.stringify (appRouter.concat (newDate)) || '[]')
                                store.commit ('updateMenulist')
                            } else {
                                sessionStorage.setItem ('menuList', '[]')
                                //store.commit ('updateMenulist')
                            }
                            resolve ()
                        })
                    }).then (() => {
                        // 加载otherApp路由
                        loadDynamicOtherAppMenu ().then (( {data} ) => {
                            sessionStorage.setItem ('otherAppList', JSON.stringify (data.data) || '[]')
                            next ({...to, replace: true})
                        })
                    })
                },0)
            }).catch(e=>{
                sessionStorage.clear();
                window.location.reload();
            })

        } else {
            next ()
        }
    }
})


/*******************************************************************************
 * Function    : afterEach
 * Description : 跳转过后的操作
 * Input       : to, 当前的界面
 * Return      : None
 *******************************************************************************/
/*router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    window.scrollTo(0, 0);
});*/

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push ( location, onResolve, onReject ) {
    if (onResolve || onReject) {
        return originalPush.call (this, location, onResolve, onReject)
    }
    return originalPush.call (this, location).catch (err => err)
}
router.onError (( error ) => {
    const pattern = /Loading chunk (\d) +failed/g
    const isChunkLoadFailed = error.message.match (pattern)
    const targetPath = router.history.pending.fullPath
    sessionStorage.setItem('interceptorMsg2',error.message);
    if (isChunkLoadFailed) {
        router.replace ('/#' + targetPath)
    }
})

function routerCom ( path ) {
    return ( resolve ) => require([`@/views/${path}`], resolve)
}
function routerChildren (children ) {
    children.forEach(v=>{
        v.component = routerCom(v.component);
        if(v.children.length >= 1){
            v.children = routerChildren(v.children)
        }
    })
    return children
}
/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes ( menuList = [], routes = []) {
    var temp = []
    let Obj = {}
    for (var i = 0; i < menuList.length; i++) {
        if (menuList[ i ].children && menuList[ i ].children.length >= 1) {
            temp = temp.concat (menuList[ i ].children)
        } else if (menuList[ i ].type === '2') {
            var route = {
                path: menuList[ i ].path,
                component: _import (`${menuList[ i ].component}`) || null,
                name: menuList[ i ].name,
                title: menuList[ i ].title,
                permissions: menuList[ i ].permissions,
                key:menuList[ i ].key,
                meta: {
                    menuId: menuList[ i ].id,
                    title: menuList[ i ].title,
                    key:menuList[ i ].key,
                    parentTitle:menuList.title,
                    subFlag:menuList[ i ].subFlag
                }
            }
            routes.push (route)
        }
    }
    if (temp.length >= 1) {
        fnAddDynamicMenuRoutes (temp, routes)
    } else {
        dynamicAppRouter.children = routes
        router.addRoutes ([
            dynamicAppRouter
        ])
    }
}

function fnAddDynamicMenuRoutesNew ( menuList = [],Pobj={}) {
    const arr=[];
    let obj ={}
    menuList.forEach(item => {
        const tmp = {...item}
        obj = {
            path: tmp.path,
            component: _import (`${tmp.component}`) || null,
            name: tmp.name,
            title: tmp.title,
            permissions: tmp.permissions,
            key: tmp.key,
            meta: {
                menuId: tmp.id,
                title: tmp.title,
                key:tmp.key
            },
        }
        if (obj.children && obj.children.length >= 1) {
            obj.children = fnAddDynamicMenuRoutesNew(obj.children,obj);
        }
        arr.push(obj)
    });
    dynamicAppRouter.children = arr
    router.addRoutes ([
        dynamicAppRouter
    ])
}
function fnAddDynamicMenuRoutesTwo ( menuList = []) {
    menuList.forEach(v=>{
        v.children = routerChildren(v.children)
        v.component = _import (`${v.component}`) || null
        dynamicAppRouter.children = v
        router.addRoutes ([
            dynamicAppRouter
        ])
    })
}
/**
 * 添加动态(otherApp)路由
 * @param {*} routeList 路由列表
 */
function fnAddDynamicOtherAppRoutes ( routeList = [] ) {
    let routes = []
    for (var i = 0; i < routeList.length; i++) {
        var route = {
            path: routeList[ i ].path,
            /*component: _import (`${routeList[ i ].component}`) || null,*/
            name: routeList[ i ].name,
            title: routeList[ i ].title,
            permissions: routeList[ i ].permissions,
            key:routeList[ i ].key,
            meta: {
                menuId: routeList[ i ].id,
                isDynamic: true,
                title: routeList[ i ].title,
                key:routeList[ i ].key
            }
        }
        routes.push (route)
    }
    otherRouter.children = routes
    router.addRoutes ([
        otherRouter,
        {path: '/*', redirect: {name: 'error-404'}}
    ])
}
